import { getApp, getImgsTempUrl } from "@/utils/cloud";
import { Message } from "element-ui";

/**
 * ckeditor5 的上传适配器
 */
export default class UploadAdapter {
  loader: any;
  constructor(loader: any) {
    this.loader = loader;
  }
  upload(): Promise<Array<string>> {
    // 参考 picturewall.vue 中的读取file的方法。
    //重置上传路径

    // 官网的方法
    return this.loader.file.then(
      (file: any) =>
        new Promise((resolve, reject) => {
          console.log("this.loader.file ", this.loader.file);
          const app = getApp();
          const reader = new FileReader();

          reader.readAsDataURL(file);
          reader.onloadend = () => {
            const cloudPath = `${
              process.env.VUE_APP_PICTURE_UPLOAD_URL
            }/${new Date().valueOf()}_${file.name}`;

            app
              .uploadFile({
                cloudPath,
                filePath: file
              })
              .then(async (res: any) => {
                // 立刻获取图片的临时下载地址
                const { fileList } = await getImgsTempUrl([res.fileID]);
                Message.success("图片缓存成功");
                console.log(fileList);
                resolve(fileList.map((file: any) => file.url));
              })
              .catch((err: any) => {
                console.log("图片上传错误", err);
                reject(err);
              });
          };
        })
    );
  }
}
